/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.modules.ap.entity.SubImport;
import com.jeeplus.modules.ap.entity.Subject;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.config.Global;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.ap.entity.Sub;
import com.jeeplus.modules.ap.service.SubService;

/**
 * 支出科目Controller
 * @author 李超辉
 * @version 2018-04-23
 */
@Controller
@RequestMapping(value = "${adminPath}/ap/sub")
public class SubController extends BaseController {

	@Autowired
	private SubService subService;
	
	@ModelAttribute
	public Sub get(@RequestParam(required=false) String id) {
		Sub entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = subService.get(id);
		}
		if (entity == null){
			entity = new Sub();
		}
		return entity;
	}
	
	/**
	 * 支出科目列表页面
	 */
	@RequiresPermissions("ap:sub:list")
	@RequestMapping(value = {"list", ""})
	public String list(Sub sub,  HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "modules/ap/subList";
	}

	/**
	 * 查看，增加，编辑支出科目表单页面
	 */
	@RequiresPermissions(value={"ap:sub:view","ap:sub:add","ap:sub:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Sub sub, Model model) {
		if (sub.getParent()!=null && StringUtils.isNotBlank(sub.getParent().getId())){
			sub.setParent(subService.get(sub.getParent().getId()));
			// 获取排序号，最末节点排序号+30
			if (StringUtils.isBlank(sub.getId())){
				Sub subChild = new Sub();
				subChild.setParent(new Sub(sub.getParent().getId()));
				List<Sub> list = subService.findList(sub); 
				if (list.size() > 0){
					sub.setSort(list.get(list.size()-1).getSort());
					if (sub.getSort() != null){
						sub.setSort(sub.getSort() + 30);
					}
				}
			}
		}
		if (sub.getSort() == null){
			sub.setSort(30);
		}
		model.addAttribute("sub", sub);
		return "modules/ap/subForm";
	}

	/**
	 * 保存支出科目
	 */
	@ResponseBody
	@RequiresPermissions(value={"ap:sub:add","ap:sub:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Sub sub, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, sub)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}

		//新增或编辑表单保存
		subService.save(sub);//保存
		j.setSuccess(true);
		j.put("sub", sub);
		j.setMsg("保存支出科目成功");
		return j;
	}
	@RequestMapping("getJson")
	@ResponseBody
	public  String getJson(){
		Sub s=new Sub();
		s.setType("1");
		StringBuffer provance=new StringBuffer();

		List<Sub> list=subService.findList(s);
		provance.append("[");

		for(Sub su:list){
			provance.append("{ 'id': '").append(su.getId()).append("','name' : '").append(su.getName()).append("','city' : [");
			Sub s0=new Sub();
			s0.setType("2");
			s0.setParent(su);
			List<Sub> l=subService.findList(s0);
			for(Sub sub:l){
				provance.append("{ 'id': '").append(sub.getId()).append("','name' : '").append(sub.getName()).append("'},");
			}
			if(l!=null&&l.size()>0){
				provance.deleteCharAt(provance.length() - 1);
			}
			provance.append("]},");
		}
		provance.deleteCharAt(provance.length() - 1);
		provance.append("]");
		return provance.toString();
	}

	@RequestMapping("getJson1")
	@ResponseBody
	public  String getJson1(){
		StringBuffer area=new StringBuffer();
		area.append("[");
		Sub s1=new Sub();
		s1.setType("3");
		List<Sub> l=subService.findList(s1);
		for(Sub subj:l){
			area.append("{ 'id': '").append(subj.getId()).append("','name' : '").append(subj.getName()).append("','pid' : '").append(subj.getParent().getId()).append("'},");
		}
		area.deleteCharAt(area.length() - 1);
		area.append("]");
		return area.toString();
	}
	@ResponseBody
	@RequestMapping(value = "getChildren")
	public List<Sub> getChildren(String parentId){
		if("-1".equals(parentId)){//如果是-1，没指定任何父节点，就从根节点开始查找
			parentId = "0";
		}
		return subService.getChildren(parentId);
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody

	@RequestMapping(value = "export")
	public AjaxJson exportFile(Sub subject, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "科目"+ DateUtils.getDate("yyyyMMddHH")+".xlsx";
			List<SubImport> list=new ArrayList<SubImport>();
			Page<Sub> page = subService.findPage(new Page<Sub>(request, response, -1), subject);
			for(Sub s:page.getList()){
				if(s.getType().equals("1")){
					SubImport sub=new SubImport();
					sub.setName(s.getName());
					sub.setType("1");
					list.add(sub);
					for(Sub ss:page.getList()){
						if(ss.getParent().getId().equals(s.getId())){
							SubImport su=new SubImport();
							su.setName(ss.getName());
							su.setType("2");
							su.setFather(s.getName());
							list.add(su);
						}
					}
				}
			}
			new ExportExcel("科目", SubImport.class).setDataList(list).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出失败！失败信息："+e.getMessage());
		}
		return j;
	}


	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("ap:income:import")
	@RequestMapping(value = "import", method= RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<SubImport> list = ei.getDataList(SubImport.class);
			for (SubImport income1 : list){
				try{
					Sub income=new Sub();
					String f=income1.getFather();
					if(f!=null&&f!=""){
					Sub s=new Sub();
					s.setName(f);
					List<Sub> subs=subService.findList(s);
					if(subs==null||subs.size()<1){
						break;
					}else{
						income.setParent(subs.get(0));
					}
					}
					income.setType(income1.getType()+"");
					income.setName(income1.getName());
					subService.save(income);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条收入记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条收入记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入收入失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/sub/?repage";
	}

	/**
	 * 下载导入收入数据模板
	 */
	@RequiresPermissions("ap:income:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "支出科目导入模板.xlsx";
			List<SubImport> list = Lists.newArrayList();
			new ExportExcel("支出科目数据", SubImport.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/sub/?repage";
	}
	
	/**
	 * 删除支出科目
	 */
	@ResponseBody
	@RequiresPermissions("ap:sub:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Sub sub, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		subService.delete(sub);
		j.setSuccess(true);
		j.setMsg("删除支出科目成功");
		return j;
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Sub> list = subService.findList(new Sub());
		for (int i=0; i<list.size(); i++){
			Sub e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("text", e.getName());
				if(StringUtils.isBlank(e.getParentId()) || "0".equals(e.getParentId())){
					map.put("parent", "#");
					Map<String, Object> state = Maps.newHashMap();
					state.put("opened", true);
					map.put("state", state);
				}else{
					map.put("parent", e.getParentId());
				}
				mapList.add(map);
			}
		}
		return mapList;
	}
	
}